package com.example.myhenggrideview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private class Model {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    ArrayList<Model> arrayList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView = (GridView) findViewById(R.id.diy_gridview);


        for (int i = 0; i <= 50; i++) {
            Model model = new Model();
            model.setName("name--" + i);
            arrayList.add(model);
        }


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        gridView.setHorizontalSpacing(5); // 设置列表项水平间距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(4); // 设置列数量=列表集合数

        GridViewAdapter adapter = new GridViewAdapter();
        gridView.setAdapter(adapter);

    }

    private class GridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, android.view.View convertView, ViewGroup parent) {
            convertView = View.inflate(getApplicationContext(), R.layout.list_item, null);
            ImageView imageView = (ImageView) convertView.findViewById(R.id.item_image);
            TextView textView = (TextView) convertView.findViewById(R.id.item_text);
            imageView.setImageResource(R.mipmap.ic_launcher);
            textView.setText(arrayList.get(position).getName());
            return convertView;
        }
    }
}
